Blockly.FieldAngle.CLOCKWISE = true;
Blockly.FieldAngle.OFFSET = 90;

// 控制标志位
let isPaused = true;
let isStopped = false;


Blockly.JavaScript.STATEMENT_PREFIX = 'highlightBlock(%1);\nawait ';
Blockly.JavaScript.addReservedWords('highlightBlock');

function highlightBlock(id) {
    workspace.highlightBlock(id);
}

Blockly.Blocks['nav_goal'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldLabelSerializable("导航到目标点"), "nav-goal-text")
            .appendField(new Blockly.FieldDropdown(blocklyList), "goal-list")
            .appendField(new Blockly.FieldCheckbox("TRUE"), "is-wait-nav")
            .appendField(new Blockly.FieldLabelSerializable("等待导航完成"), "is-wait-nav-text");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(230);
    this.setTooltip("");
    this.setHelpUrl("");
    }
};

Blockly.Blocks['relative_move'] = {
    init: function() {
        this.appendDummyInput()
            .setAlign(Blockly.ALIGN_RIGHT)
            .appendField(new Blockly.FieldLabelSerializable("底盘相对移动"), "relative-move-text")
            .appendField(new Blockly.FieldLabelSerializable(" x:"), "relative-move-x-text")
            .appendField(new Blockly.FieldNumber(0, -100, 100), "relative-move-x")
            .appendField("cm;")
            .appendField(new Blockly.FieldLabelSerializable(" y:"), "relative-move-y-text")
            .appendField(new Blockly.FieldNumber(0, -100, 100), "relative-move-y")
            .appendField("cm;")
            .appendField(new Blockly.FieldLabelSerializable(" angle:"), "relative-move-angle-text")
            .appendField(new Blockly.FieldAngle(0), "relative-move-angle")
            .appendField("cm;");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(230);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Blocks['track'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldLabelSerializable("机器人对准AR码"), "track-text")
            .appendField(new Blockly.FieldNumber(0, 0, 100), "track-mark-id");
        this.appendStatementInput("track-next")
            .setCheck(null)
            .appendField(new Blockly.FieldLabelSerializable("成功"), "track-input-text");
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(230);
    this.setTooltip("");
    this.setHelpUrl("");
    }
};

Blockly.Blocks['ros_start'] = {
    init: function() {
        Blockly.BlockSvg.START_HAT = true;
        this.appendDummyInput()
            .appendField(new Blockly.FieldLabelSerializable("机器人启动"), "ros-start-text");
        this.appendStatementInput("ros-start-next")
            .setCheck(null);
        this.setColour(230);
        // this.svgGroup.START_HAT = true;
        // this.BlockSvg.START_HAT = true;
    this.setTooltip("");
    this.setHelpUrl("");
    }
};

javascript.javascriptGenerator.forBlock['nav_goal'] = function(block, generator) {
    var field_nav_goal_text = block.getFieldValue('nav-goal-text');
    var dropdown_goal_list = block.getFieldValue('goal-list');
    var checkbox_is_wait_nav = block.getFieldValue('is-wait-nav') === 'TRUE';
    var field_is_wait_nav_text = block.getFieldValue('is-wait-nav-text');
    // TODO: Assemble javascript into code variable.
    // var code = 'await RobotBase.goto_NavGoal(PoseList["'+dropdown_goal_list+'"])\n';
    var code = 'RobotBase.goto_NavGoal(PoseList["'+dropdown_goal_list+'"]);\n';
    return code;
};

javascript.javascriptGenerator.forBlock['relative_move'] = function(block, generator) {
    var field_relative_move_text = block.getFieldValue('relative-move-text');
    var field_relative_move_x_text = block.getFieldValue('relative-move-x-text');
    var number_relative_move_x = block.getFieldValue('relative-move-x');
    var field_relative_move_y_text = block.getFieldValue('relative-move-y-text');
    var number_relative_move_y = block.getFieldValue('relative-move-y');
    var field_relative_move_angle_text = block.getFieldValue('relative-move-angle-text');
    var angle_relative_move_angle = block.getFieldValue('relative-move-angle');
    // TODO: Assemble javascript into code variable.
    // var code = 'await RobotBase.relative_move('+number_relative_move_x+','+number_relative_move_y+','+angle_relative_move_angle+')\n';
    var code = 'RobotBase.relative_move('+number_relative_move_x+','+number_relative_move_y+','+angle_relative_move_angle+');\n';
    return code;
};

javascript.javascriptGenerator.forBlock['track'] = function(block, generator) {
    var field_track_text = block.getFieldValue('track-text');
    var number_track_mark_id = block.getFieldValue('track-mark-id');
    var field_track_input_text = block.getFieldValue('track-input-text');
    var statements_track_next = generator.statementToCode(block, 'track-next');
    // TODO: Assemble javascript into code variable.
    // var code = 'await RobotBase.goto_track('+number_track_mark_id+')\n'+statements_track_next;
    var code = 'RobotBase.goto_track('+number_track_mark_id+')\n'+statements_track_next;
    return code;
};

javascript.javascriptGenerator.forBlock['ros_start'] = function(block, generator) {
    var field_ros_start_text = block.getFieldValue('ros-start-text');
    var statements_ros_start_next = generator.statementToCode(block, 'ros-start-next');
    // TODO: Assemble javascript into code variable.
    // var code = 'async function run(){var RobotBase = new robot_api.RobotBase({ros:ros})\n'+statements_ros_start_next+'}\nrun()';
    var code = 'var RobotBase = new robot_api.RobotBase({ros:ros});\n';
    return code;
};

BlocklyStorage.backupOnUnload = function(opt_workspace) {
    var workspace = opt_workspace || Blockly.getMainWorkspace();
    window.addEventListener('unload',
        function() {
            BlocklyStorage.backupBlocks_(workspace);
    }, false);
};

/**
 * Restore code blocks from localStorage.
 * @param {Blockly.WorkspaceSvg=} opt_workspace Workspace. 
 */
BlocklyStorage.restoreBlocks = function(opt_workspace) {
    var url = window.location.href.split('#')[0];
    if ('localStorage' in window && window.localStorage[url]) {
        var workspace = opt_workspace || Blockly.getMainWorkspace();
        var xml = Blockly.utils.xml.textToDom(window.localStorage[url]);
        Blockly.Xml.domToWorkspace(xml, workspace);
    }
};

var robot_run = document.getElementById('robot-run');
var robot_stop = document.getElementById('robot-stop');


robot_run.onclick = function() {
    if(ros_is_linked){
        isPaused = false
        if (isStopped){
            rei_log('继续运行');
        }else{
            generateJsCode();
        }
        isStopped = false
    }else{
        alert('程序未启动')
    }
}

robot_stop.onclick = function() {
    if(isPaused==false){
        if (isStopped) {
            if (window.confirm("是否终止任务？")){
                isPaused = true;
                isStopped = false;
            }
        }else{
            isStopped = true;
            rei_log('暂停运行');
        }
    }else{
        alert('没有在运行的程序')
    }
}
// 运行脚本的函数
function generateJsCode() {
    // 生成 JavaScript 代码
    var code = Blockly.JavaScript.workspaceToCode(workspace);
    // 插入控制逻辑
    runcode = `
        async function innerRun() {
            rei_log('开始执行任务');
            while (isStopped) { await new Promise(r => setTimeout(r, 100));}
            var RobotBase = new robot_api.RobotBase({ros:ros});
            ${code.replace(/(.*)/g, 'while (isStopped) { await new Promise(r => setTimeout(r, 100)); }\nif (isPaused) { \nhighlightBlock("");\nrei_log("终止运行");\nreturn true; }\n$1')}
            highlightBlock("");
            rei_log('任务执行结束');
        }
        innerRun();
    `;
    // 执行生成的代码
    try {
        eval(runcode)
        // new Function('highlightBlock', 'isPaused', 'isStopped', runcode)(highlightBlock, isPaused, isStopped);
    } catch (error) {
        console.error('脚本执行出错:', error);
    }
}

